#!/bin/bash

# 设置配置主目录
if [ -z "$CONFIG_HOME" ]; then
  export CONFIG_HOME="${HOME}/.mac_sync"
fi

LOG_FILE="${CONFIG_HOME}/logs/health_check_$(date +%Y%m%d).log"

# 确保日志目录存在
mkdir -p "${CONFIG_HOME}/logs"

echo "[$(date +%Y-%m-%d\ %H:%M:%S)] 开始健康检查" >> "$LOG_FILE"

# 检查macOS 14系统卷是否挂载
if [ ! -d "/Volumes/Sun" ]; then
    echo "[$(date +%Y-%m-%d\ %H:%M:%S)] 错误: macOS 14系统卷未挂载" >> "$LOG_FILE"
    osascript -e 'display notification "macOS 14系统卷未挂载，部分应用可能无法使用" with title "应用访问警告"'
    diskutil mount "/Volumes/Sun" >> "$LOG_FILE" 2>&1
fi

# 检查应用目录链接
if [ ! -L "/Applications" ]; then
    echo "[$(date +%Y-%m-%d\ %H:%M:%S)] 错误: 应用目录不是符号链接" >> "$LOG_FILE"
    osascript -e 'display notification "应用目录链接丢失，请运行设置脚本修复" with title "应用访问错误"'
else
    link_target=$(readlink "/Applications")
    if [ "$link_target" != "/Volumes/Sun/Applications" ]; then
        echo "[$(date +%Y-%m-%d\ %H:%M:%S)] 错误: 应用目录链接指向错误位置 ($link_target)" >> "$LOG_FILE"
    fi
fi

# 检查损坏的链接
broken_links=$(find "/Applications" -maxdepth 1 -type l -exec test ! -e {} \; -print | wc -l)
if [ $broken_links -gt 0 ]; then
    echo "[$(date +%Y-%m-%d\ %H:%M:%S)] 警告: 发现$broken_links个损坏的链接" >> "$LOG_FILE"
    find "/Applications" -maxdepth 1 -type l -exec test ! -e {} \; -print >> "$LOG_FILE"
fi

# 检查系统应用链接
for app in "/Applications"/*.app; do
    app_name=$(basename "$app")
    if [ -e "/Applications.original/$app_name" ] && [ ! -L "$app" ]; then
        echo "[$(date +%Y-%m-%d\ %H:%M:%S)] 警告: 系统应用$app_name没有使用本地版本" >> "$LOG_FILE"
    fi
done

echo "[$(date +%Y-%m-%d\ %H:%M:%S)] 健康检查完成" >> "$LOG_FILE"
